package com.weipeep.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.weipeep.common.annotation.Log;
import com.weipeep.common.base.BaseController;
import com.weipeep.common.config.Constant;
import com.weipeep.common.domain.Tree;
import com.weipeep.common.type.EnumErrorCode;
import com.weipeep.common.utils.IdGenerator;
import com.weipeep.common.utils.MD5Utils;
import com.weipeep.common.utils.Result;
import com.weipeep.common.utils.ShiroUtils;
import com.weipeep.oss.domain.FileDO;
import com.weipeep.oss.service.FileService;
import com.weipeep.sys.domain.MenuDO;
import com.weipeep.sys.domain.UserDO;
import com.weipeep.sys.service.MenuService;
import com.weipeep.sys.service.UserService;
import com.weipeep.sys.vo.UserRegisterVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | wangyun</small>
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Resource
    private UserService userService;
    @Autowired
    IdGenerator idGenerator;

    @Log("请求访问主页")
    @GetMapping({ "/admin/index" })
    String adminIndex(Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        model.addAttribute("username", getUser().getUsername());
        FileDO fileDO = fileService.selectById(getUser().getPicId());
        model.addAttribute("picUrl", fileDO == null ? "/img/chuanjian.jpg" : fileDO.getUrl());
        return "index_v1";
    }

    @GetMapping("/login")
    String login(Model model) {
        model.addAttribute("title","登陆");
        model.addAttribute("html",2);
        UserDO userDO = getUser();
        if (userDO==null){
            model.addAttribute("url","/login");
            model.addAttribute("content","登陆");
            model.addAttribute("ifLogin",false);
        }else {
            model.addAttribute("url","/admin/index");
            model.addAttribute("content",userDO.getName());
            model.addAttribute("ifLogin",true);
        }
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    Result<String> ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return Result.ok();
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }
    @GetMapping("/getInfo")
    @ResponseBody
    public UserDO fetchUserInfo(String email){
        UserDO userDO = userService.getUserInfo(email);
        return userDO;
    }


//    public static void main(String[] args) {
//        System.out.println(MD5Utils.encrypt("admin", "admin"));
//    }
    @Log("退出")
    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }
    @Log("welcome")
    @RequestMapping(value = "/welcome" ,method = RequestMethod.GET)
    String main(Model model) {
        return "welcome";
    }

    @RequestMapping(value = "/register",method = RequestMethod.GET)
    String register(Model model) {
        model.addAttribute("title","注册");
        model.addAttribute("html",2);
        UserDO userDO = getUser();
        if (userDO==null){
            model.addAttribute("url","/login");
            model.addAttribute("content","登陆");
            model.addAttribute("ifLogin",false);
        }else {
            model.addAttribute("url","/admin/index");
            model.addAttribute("content",userDO.getName());
            model.addAttribute("ifLogin",true);
        }
        return "register";
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> checkUsername(UserRegisterVo userRegisterVo){
        UserDO userCheckDO = new UserDO();
        userCheckDO.setUsername(userRegisterVo.getUsername());
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>(userCheckDO);
        List<UserDO> userDOList = userService.selectList(wrapper);
        if (userDOList.size()>0){
            return Result.fail().setMsg("账号已存在");
        }else {
            userRegisterVo.setStatus(1);
            userRegisterVo.setAuditStatus(Constant.UserAuditStatus.NOT_AUDIT);
            userRegisterVo.setGmtCreate(Calendar.getInstance().getTime());
            userRegisterVo.setGmtModified(Calendar.getInstance().getTime());
            userRegisterVo.setUserType(Constant.UserType.MEMBER);
            userRegisterVo.setPassword(MD5Utils.encrypt(userRegisterVo.getUsername(), userRegisterVo.getPassword()));
            userRegisterVo.setId(idGenerator.nextId());
            userService.insertUser(userRegisterVo);
            return Result.ok();
        }
    }
    @GetMapping("/register1")
    String register1(Model model) {
        model.addAttribute("html",2);
        return "register1";
    }
    @GetMapping("/")
    String index() {
        return "redirect:/front/index";
    }

    @GetMapping("/mobile")
    String mobileIndex() {
        return "mobile";
    }

    @GetMapping("/front/register")
    String frontRegister(){return "/front/register";}

    @GetMapping("/front/login")
    String frontLogin(){return "/front/login";}

    @GetMapping("/403")
    String error403() {
        return "403";
    }

}
